package org.client.iot.ui.device.network;

import android.annotation.SuppressLint;

import com.lucky.base.network.NetworkApi;
import com.lucky.base.network.observer.BaseObserver;
import com.lucky.utils.FastjsonUtils;
import com.lucky.utils.log.LogUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.picker.widget.TimePickerView;
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder;

import org.client.iot.databinding.ActivityNetworkDataUploadBinding;
import org.client.iot.http.ApiService;
import org.client.iot.http.BaseDevReq;
import org.client.iot.util.MMKVUtils;
import org.client.iot.util.TimeUtils;
import org.tzw.template.base.BaseActivity;

import java.util.LinkedHashMap;
import java.util.Map;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @Date 2025/8/20 9:32
 * @Description 数据上传
 */

public class DataUploadActivity extends BaseActivity<ActivityNetworkDataUploadBinding> {
    private MiniLoadingDialog mMiniLoadingDialog;

    @Override
    protected void initView() {
        setSupportActionBar(mRoot.toolbarDataUpload.toolbarPageHead);
        mRoot.toolbarDataUpload.textViewTitle.setText("数据上传");
        mRoot.txtServerIp.setText((String) MMKVUtils.getInstance().get("DevServerIP", ""));
        mRoot.txtServerPort.setText((String) MMKVUtils.getInstance().get("DevServerPort", ""));
        showLoading("查询设备全部数据数量中..");
        getOfflineDataQuantity();
    }

    @Override
    protected void initListener() {
        mRoot.toolbarDataUpload.imgBack.setOnClickListener(v -> {
            finish();
        });
        mRoot.btnGetStartTime.setOnClickListener(v -> {
            TimePickerView mDatePicker = new TimePickerBuilder(this, (date, v12) -> mRoot.txtStartTime.setText(TimeUtils.getYearAndMonthAndDayTime(date))).setTitleText("日期选择").build();
            mDatePicker.show();
        });
        mRoot.btnGetEndTime.setOnClickListener(v -> {
            TimePickerView mDatePicker = new TimePickerBuilder(this, (date, v1) -> mRoot.txtEndTime.setText(TimeUtils.getYearAndMonthAndDayTime(date))).setTitleText("日期选择").build();
            mDatePicker.show();
        });
        mRoot.btnDataUpload.setOnClickListener(v -> {
            String startDate = mRoot.txtStartTime.getText().toString();
            String endDate = mRoot.txtEndTime.getText().toString();
            if (startDate.isEmpty() || endDate.isEmpty()) {
                showToastLong("请选择开始日期和结束日期");
                return;
            }
            String type = mRoot.spDataUploadType.getSelectedItem().toString();
            if (type.isEmpty()) {
                showToastShort("请选择类型");
                return;
            }
            if (mRoot.txtDataQuantity.getText().toString().isEmpty()) {
                showToastShort("请先获取当前离线保存数据数量");
                return;
            }
            int dataQuantity = Integer.parseInt(mRoot.txtDataQuantity.getText().toString());
            showLoading("数据上传中...");
            dataUpload(type, dataQuantity, startDate, endDate);
        });
    }


    //查询设备全部数据数量
    private void getOfflineDataQuantity() {
        Observable<BaseDevReq<Object>> compose = NetworkApi.createService(ApiService.class, "dev").getOfflineDataQuantity().compose(NetworkApi.applySchedulers(new BaseObserver<BaseDevReq<Object>>() {
            @SuppressLint({"CheckResult", "SetTextI18n"})
            @Override
            public void onSuccess(BaseDevReq<Object> req) {
                if (req == null) {
                    return;
                }
                runOnUiThread(() -> {
                    disLoading();
                    LogUtils.i("查询设备全部数据数量req==", FastjsonUtils.toJsonString(req));
                    showToastLong(req.getMessage());
                    if (req.getData() != null) {
                        try {
                            // 将对象先转为标准 JSON 字符串，再解析
                            String jsonData = FastjsonUtils.toJsonString(req.getData());
                            String dataQuantity = FastjsonUtils.getItemData(jsonData, "dataQuantity");
                            // 处理浮点数显示问题
                            if (dataQuantity != null && dataQuantity.contains(".")) {
                                try {
                                    double value = Double.parseDouble(dataQuantity);
                                    int intValue = (int) value;
                                    // 如果小数部分为0，则显示为整数
                                    if (value == intValue) {
                                        mRoot.txtDataQuantity.setText(String.valueOf(intValue));
                                    } else {
                                        mRoot.txtDataQuantity.setText(dataQuantity);
                                    }
                                } catch (NumberFormatException e) {
                                    mRoot.txtDataQuantity.setText(dataQuantity);
                                }
                            } else {
                                mRoot.txtDataQuantity.setText(dataQuantity != null ? dataQuantity : "0");
                            }
                        } catch (Exception e) {
                            LogUtils.e("解析 dataQuantity 失败", String.valueOf(e));
                            mRoot.txtDataQuantity.setText("0");
                        }
                    }
                });

            }

            @SuppressLint("CheckResult")
            @Override
            public void onFailure(Throwable e) {
                runOnUiThread(() -> {
                    disLoading();
                    showToastLong(e.getMessage());
                });

            }
        }));
    }

    //数据上传
    private void dataUpload(String type, int dataQuantity, String startTime, String endTime) {
        String params = FastjsonUtils.toJsonString(dataUploadParams(type, dataQuantity, startTime, endTime));
        Observable<BaseDevReq<Object>> compose = NetworkApi.createService(ApiService.class, "dev").dataUpload(RequestBody.create(MediaType.parse("application/json"), params)).compose(NetworkApi.applySchedulers(new BaseObserver<BaseDevReq<Object>>() {
            @SuppressLint({"CheckResult", "SetTextI18n"})
            @Override
            public void onSuccess(BaseDevReq<Object> req) {
                if (req == null) {
                    return;
                }
                runOnUiThread(() -> {
                    disLoading();
                    LogUtils.i("数据上传req==", req.toString());
                    showToastLong(req.getMessage());

                });

            }

            @SuppressLint("CheckResult")
            @Override
            public void onFailure(Throwable e) {
                runOnUiThread(() -> {
                    disLoading();
                    showToastLong(e.getMessage());
                });

            }
        }));
    }

    private Map<String, Object> dataUploadParams(String type, int dataQuantity, String startTime, String endTime) {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("type", type);
        params.put("data_quantity", dataQuantity);
        params.put("start_time", startTime);
        params.put("end_time", endTime);
        return params;
    }

    private void showLoading(String msg) {
        runOnUiThread(() -> {
            mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, msg);
            mMiniLoadingDialog.show();
        });
    }

    private void disLoading() {
        runOnUiThread(() -> {
            if (mMiniLoadingDialog != null) {
                mMiniLoadingDialog.dismiss();
            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        disLoading();
    }
}
